package com.typhosoft.jcommon.network;

import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by Mario on 21/03/2014.
 */
public class CClient {

    Client client;

    public CClient() {
        this(null);
    }

    public CClient(Listener l) {
        client = new Client();
        client.start();

        // For consistency, the classes to be sent over the network are
        // registered by the same method for both the client and server.
        CNetwork.register(client);

        if (l != null) {
            client.addListener(l);
        }

        // We'll do the connect on a new thread so the ChatFrame can show a progress bar.
        // Connecting to localhost is usually so fast you won't see the progress bar.
        new Thread("Connect") {
            public void run() {
                try {
                    client.connect(5000, CNetwork.serverHost, CNetwork.port);
                    // Server communication after connection can go here, or in Listener#connected().
                } catch (IOException ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Error On Connection: ", ex);
                }
            }
        }.start();
    }

    public void send(Object message) throws IOException {
        if(!client.isConnected()){
            new Thread("Reconnect") {
                public void run() {
                    try {
                        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Try to reconnect: ");
                        client.reconnect();
                        // Server communication after connection can go here, or in Listener#connected().
                    } catch (IOException ex) {
                        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Error On Connection: ", ex);
                    }
                }
            }.start();
            return;
        }
        client.sendTCP(message);
    }

    public Connection getConnection(){
        return client;

    }
    public void stop() {
        client.stop();
    }

    public void addListener(Listener listener) {
        client.addListener(listener);
    }

    public void reconnect() throws IOException {
        client.reconnect();
    }
}
